/*
 * @(#)JsonViewResolver.java
 *
 * Copyright 2011 Xinhua Online, Inc. All rights reserved.
 */

package com.winxuan.channel.support.view.json;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractCachingViewResolver;

/**
 * description
 * 
 * @author liuan
 * @version 1.0,2011-6-16
 */
public class JsonViewResolver extends AbstractCachingViewResolver {

	private String prefix = "";
	private String suffix = "";

	@Override
	protected View loadView(String viewName, Locale locale) throws Exception {
		JsonView jsonView = new JsonView();
		List<Pattern> includeProperties = new ArrayList<Pattern>();
		String jsonTemplateFile = prefix + viewName + suffix;
		jsonView.setJsonTemplateFile(jsonTemplateFile);
		jsonTemplateFile = getServletContext().getRealPath(jsonTemplateFile);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(jsonTemplateFile));
		} catch (FileNotFoundException e) {
			jsonView.setError(true);
		}
		if (reader != null) {
			String line = null;
			while ((line = reader.readLine()) != null) {
				if (!"".equals(line.trim())) {
					includeProperties.add(Pattern.compile(line.trim()));
				}
			}
			jsonView.setIncludeProperties(includeProperties);
		}
		return jsonView;
	}
	
	@Override
	protected Object getCacheKey(String viewName, Locale locale) {
		return viewName;
	}

	public void setPrefix(String prefix) {
		this.prefix = (prefix != null ? prefix : "");
	}

	public String getPrefix() {
		return this.prefix;
	}

	public void setSuffix(String suffix) {
		this.suffix = (suffix != null ? suffix : "");
	}

	public String getSuffix() {
		return this.suffix;
	}

}
